<template>
  <div>
    <!-- 新增 修改 -->
    <el-dialog
      width="500px"
      title="title"
      :title="type == 'add' ? $t('添加') : $t('编辑')"
      destroy-on-close
      append-to-body
      :visible.sync="show"
      :before-close="cancel"
    >
      <el-form
        ref="elForm"
        :model="form"
        :rules="rules"
        label-width="130px"
        label-position="right"
      >
        <!-- 租户 推荐人/分成 推荐人上级/分成 总公司/分成  -->

        <el-form-item label="注册卖家:" prop="referrerRegisterId">
          <el-select
            style="width: 100%"
            clearable
            filterable
            v-model="form.referrerRegisterId"
          >
            <el-option
              :label="item.name"
              :value="item.distrId"
              :key="item.distrId"
              v-for="item in distributorList"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推荐卖家:" prop="referrerId">
          <el-select
            filterable
            style="width: 100%"
            clearable
            v-model="form.referrerId"
          >
            <el-option
              :label="item.name"
              :value="item.distrId"
              :key="item.distrId"
              v-for="item in distributorList"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推荐卖家上级:">
          <el-select
            filterable
            style="width: 100%"
            clearable
            v-model="form.referrerSuperId"
          >
            <el-option
              :label="item.name"
              :value="item.distrId"
              :key="item.distrId"
              v-for="item in distributorList"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="租户:">
          <el-input v-model="form.mail" />
        </el-form-item> -->
        <el-form-item label="推荐人/分成:" prop="referrerProportion">
          <el-input type="number" v-model.number="form.referrerProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <el-form-item
          label="推荐人上级/分成:"
          :prop="form.referrerSuperId ? 'referrerSuperProportion' : ''"
        >
          <el-input type="number" v-model.number="form.referrerSuperProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="总公司/分成:" prop="headOfficeProportion">
          <el-input type="number" v-model.number="form.headOfficeProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" plain @click="cancel">
          <!-- cancel -->
          {{ $t("取消") }}
        </el-button>
        <!-- ******************* 新增 ******************* -->
        <el-button
          v-if="type == 'add'"
          size="small"
          plain
          @click="handleAdd"
          type="primary"
        >
          <!-- 确定 -->
          {{ $t("确定") }}
        </el-button>
        <!-- ******************* 新增 end ******************* -->
        <!-- ******************* 修改 ******************* -->
        <el-button
          v-if="type == 'edit'"
          size="small"
          plain
          @click="handleEdit"
          type="primary"
        >
          <!-- 修改 -->
          {{ $t("编辑") }}
        </el-button>
        <!-- ******************* 修改 end ******************* -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDistributorList,
  insertDistributorProportion,
  edit,
} from "@/api/platform/divisionRelation";

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: {},
    },
    /**
     * type
     */
    type: {
      type: String,
      required: true,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      distributorList: [],
      form: {
        referrerRegisterId: "",
        referrerId: "",
        referrerSuperId: "",
        referrerProportion: "",
        referrerSuperProportion: "",
        headOfficeProportion: "",
      },
      rules: {
        referrerRegisterId: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        referrerId: [{ required: true, message: "请选择", trigger: "blur" }],
        referrerSuperId: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        referrerProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: "blur",
          },
        ],
        referrerSuperProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: "blur",
          },
        ],
        headOfficeProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.resetForm();
        this.getDistributorList();
        if (this.type == "edit") {
          Object.keys(this.formData).forEach((key) => {
            this.form[key] = this.formData[key];
          });
          console.log(`this.form ==>`, JSON.parse(JSON.stringify(this.form)));
        }
      }
    },
  },
  methods: {
    /**验证推荐人 */
    valid(rule, value, callback) {
      // console.log(
      //   `rule, value, ==>`,
      //   JSON.parse(JSON.stringify({ rule, value }))
      // );
      const { field } = rule;
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form;

      console.log(`value ==>`,value);
      if (!value) {
        return callback(new Error("请输入"));
      }

      if (field == "referrerProportion" /**推荐人 */) {
        if (+referrerProportion > 100 || +referrerProportion < 0) {
          return callback(new Error("取值范围在0~100"));
        }
      }

      if (field == "referrerSuperProportion" /**推荐人上级 */) {
        if (+referrerSuperProportion > 100 || +referrerSuperProportion < 0) {
          return callback(new Error("取值范围在0~100"));
        }
      }

      if (field == "headOfficeProportion" /**总公司 */) {
        if (+headOfficeProportion > 100 || +headOfficeProportion < 0) {
          return callback(new Error("取值范围在0~100"));
        }
      }

      const total =
        +referrerProportion + +referrerSuperProportion + +headOfficeProportion;

      if (total > 100) {
        callback(new Error("总和不能超过100"));
      }
      return callback();
    },
    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ""));
    },
    handleIs100() {
      // 判断分成相加是否为100
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form;
      const total =
        +referrerProportion + +referrerSuperProportion + +headOfficeProportion;

      if (total != 100) {
        return false;
      }
      return true;
    },
    handleAdd() {
      const flag = this.handleIs100();
      if (this.form.referrerSuperId && !flag) {
        return this.$message.error("比例总和必须为100");
      }
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          insertDistributorProportion(this.form).then((res) => {
            const { code, data, msg } = res;
            if (code === 200) {
              this.$message({ type: 'success', message: msg})
;
              this.cancel();
              this.$emit("getList");
            }
          });
        }
      });
    },
    handleEdit() {
      const flag = this.handleIs100();
      if (this.form.referrerSuperId && !flag) {
        return this.$message.error("比例总和必须为100");
      }
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          edit(this.form).then((res) => {
            const { code, data, msg } = res;
            if (code === 200) {
              this.$message({ type: 'success', message: msg})
;
              this.cancel();
              this.$emit("getList");
            }
          });
        }
      });
    },

    getDistributorList() {
      const data = {};
      getDistributorList(data).then((res) => {
        const { code, data, msg } = res;
        if (code === 200) {
          console.log(`res ==>`, JSON.parse(JSON.stringify(res)));
          this.distributorList = data;
        }
      });
    },
    cancel() {
      this.$emit("update:show", false);
    },
  },
};
</script>
<style scoped lang="scss">
._item {
  display: flex;
  &_name {
    flex: 2;
    text-align: center;
  }
  &_input {
    flex: 3;
  }
}
</style>
